/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年9月18日
 *******************************************************************************/

package com.hualife.md.common;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hualife.md.constants.APIConstants;
import com.hualife.support.exception.BusinessException;

/**
 * @description: 使用切面注解controllerAdvice控制异常处理
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */

// 指定增强范围为使用RestContrller注解的控制器
@ControllerAdvice(annotations = RestController.class)
public class RestExceptionHandler {

	private static final Logger logger = LoggerFactory
			.getLogger(RestExceptionHandler.class);

	@ExceptionHandler(Throwable.class)
	@ResponseBody
	private Map<String, String> handleException(Throwable ex) {
		logger.info("使用RestController注解的控制器出现异常！");
		ex.printStackTrace();
		Map<String, String> pMap = new HashMap<String, String>();
		
		if (ex instanceof BusinessException) {
			pMap.put(APIConstants.RESULT_CODE, APIConstants.RESULT_FAIL);
			pMap.put(APIConstants.RESULT_MESSAGE, ex.getMessage());
		} else {
			pMap.put(APIConstants.RESULT_CODE, APIConstants.RESULT_EXCEPTION);
			pMap.put(APIConstants.RESULT_MESSAGE, "系统处理异常，原因是：" + ex.getMessage());
		}
		return pMap;
	}

}

/*
 * 修改历史 $Log$
 */